﻿<%@ WebHandler Language="C#" Class="HandlerFactory" %>

using System;
using System.Web;

public class HandlerFactory : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Execute(context);
    }

    void Execute(HttpContext context)
    {
        //根据请求的Url,通过反射取得处理该请求的类
        string url = context.Request.Url.AbsolutePath;
        string typename = context.Request["class"];
        string methodname = context.Request["methodname"];
        TipDuck.Bll.ajaxfactory fac = new TipDuck.Bll.ajaxfactory();

        Type type = fac.GetType().Assembly.GetType(typename, false, true);

        if (type != null)
        {
            //取得类的无参数构造函数
            var constructor = type.GetConstructor(new Type[0]);
            //调用构造函数取得类的实例
            var obj = constructor.Invoke(null);
            //查找请求的方法
            var method = type.GetMethod(methodname);
            if (method != null)
            {
                var parameters = method.GetParameters();
                object[] args = null;
                if (parameters.Length > 0)
                {
                    args = new object[parameters.Length];
                    for (int x = 0; x < parameters.Length; x++)
                    {
                        args[x] = Convert.ChangeType(context.Request.Form[parameters[x].Name], parameters[x].ParameterType);
                    }
                }
                //执行方法并输出响应结果
                context.Response.Write(method.Invoke(obj, args));
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}